package io.github.fb513.transport.registry;

import com.google.common.net.HostAndPort;
import com.orbitz.consul.Consul;
import com.orbitz.consul.model.agent.ImmutableRegCheck;
import com.orbitz.consul.model.agent.ImmutableRegistration;
import io.github.fb513.transport.config.BootstrapConfig;
import io.github.fb513.transport.config.ConsulConfig;
import io.github.fb513.transport.config.ImConfig;

/**
 * @author fengbo
 * @since 2023/12/29 14:18
 */
public class ConsulRegistry {

    private final BootstrapConfig bootstrapConfig;
    private final Consul consul;

    public ConsulRegistry(BootstrapConfig bootstrapConfig) {
        this.bootstrapConfig = bootstrapConfig;
        ConsulConfig consulConfig = bootstrapConfig.getConsul();
        consul = Consul.builder().withUrl("http://" + consulConfig.getHost() + ":" + consulConfig.getPort()).withPing(false).build();
    }

    public void serviceRegister() {
        ImConfig imConfig = bootstrapConfig.getIm();
        ConsulConfig consulConfig = bootstrapConfig.getConsul();
        ImmutableRegCheck check = ImmutableRegCheck.builder().tcp(imConfig.getIpAddress() + ":" + imConfig.getPort())
                .interval("10s").timeout("5s").deregisterCriticalServiceAfter("5s").build();
        ImmutableRegistration registration = ImmutableRegistration.builder().id(imConfig.getIpNum() + "_" + imConfig.getPort())
                .name(consulConfig.getServiceName())
                .address(imConfig.getIpAddress()).port(imConfig.getPort()).check(check).build();
        consul.agentClient().register(registration);
    }
}
